<?php
namespace app\mp\admin;

use app\common\service\Factory;
use app\system\admin\Admin;
use app\common\service\Material as MaterialService;
use app\common\service\Sku as SkuService;
use app\common\service\Order as OrderService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderUser as OrderUserService;
use think\Console;
use app\common\service\SkuMaterial as SkuMaterialService;
use app\common\service\Stock as StockService;
use app\common\service\MaterialStock as MaterialStockService;
use app\common\service\SkuStockMap as SkuStockMapService;
use jinpeng\Jinpeng;
use think\Db;

/**
 * 订单进度
 * @author King
 *
 */
class Order extends Admin
{

	public function initialize() {
		parent::initialize();
	}
	public function index()
	{
		$factoryKV = getFactoryKV(false);
		$factoryOutgoKV = getFactoryOutgoKV(null);
		$factoryOutgoGbFidsKV = getFactoryOutgoGbFactoryIdsKV(1);
		$systemUserKV = getSystemUserKV(null);
		$groupKV = getGroupKV(0);
		if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
			$where      = $data = [];
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$factorId      = $this->request->param('factory_id/d', 0);
			$isAutoImport      = $this->request->param('is_auto_import/d', 0);
			$orderStatus    = $this->request->param('order_status/s');
			$orderType    = $this->request->param('type/s','');
			$breakType    = $this->request->param('break_type/s','');
			$sku    = $this->request->param('sku/s');
			$clientOrdernum    = $this->request->param('client_ordernum/s');
			$createDateRange    = $this->request->param('create_date_range/s');
			$overDateRange    = $this->request->param('over_date_range/s');
			$caichuangOverDateRange    = $this->request->param('caichuang_over_date_range/s');
			$statType    = $this->request->param('stat_type/s', '');
			$export     = $this->request->param('export/d', 0);
			$orderby     = $this->request->param('orderby/s', '');
			if ($export) {
				set_time_limit(0);
				ini_set('memory_limit', '1024M');
				$page = 1;
				$limit = 99999;
			}

			if ($orderStatus == 99) $where[] = ['status', '=', 99];
			elseif ($orderStatus == 999) $where[] = ['client_status', '=', 99];
			elseif($clientOrdernum == '') $where[] = ['status', 'in', [0,1,2]];
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['ext_id', 'like', "%" . $ext_id . "%"];
                    break;
            }

            //订单加一级
            order_level($where);
            factory_id_level($factorId,$where);
//			if ($factorId) {
//				$where[] = ['factory_id', '=', $factorId];
//			}
			if ($isAutoImport) {
				$where[] = ['is_auto_import', '=', $isAutoImport];
			}

			if ($statType != '') {
				$cacheKeyMap = ['cg' => STAT_CG, 'cj' => STAT_CJ,'chej' => STAT_CHEJ, 'wb' => STAT_WB,'dch' => STAT_DCH, 'hj' => STAT_HJ,'cpwf_cg' => STAT_CPWFCG, 'cpwf_cj' => STAT_CPWFCJ,'cpwf_hj' => STAT_CPWFHJ];
				$cacheKey = arrayGet($cacheKeyMap, $statType, '') . ADMIN_ID;
				$where[] = ['id', 'in', cache($cacheKey)];
			}
            $whereOrderType='';
            if($orderType != ''){
                if($orderType=='my_return_first' ||  $orderType=='my_first'){//返单第一次、第一次做
                    $where[] = ['type_ext', '=',$orderType];
                    $whereOrderType = ' IFNULL(remark,"") !="尾货" ';
                }else{
                    $where[] = ['type', '=', $orderType];
                }
            }

			if ($orderStatus != '') {
				switch ($orderStatus){
					case 1:
						$where[] = ['caigou_status', '=', 0];
						break;
					case 2:
						$where[] = ['caigou_status', '=', 1];
						$where[] = ['caichuang_status', '=', 0];
						break;
					case 3:
						$where[] = ['caichuang_status', '=', 1];
						$where[] = ['chejian_status', '=', 0];
						break;
					case 4:
						$where[] = ['chejian_status', '=', 1];
						$where[] = ['tail_status', '=', 0];
						break;
					case 5:
						$where[] = ['tail_status', '=', 1];
						$where[] = ['real_shipment_status', '=', 0];
						break;
					case 6:
						$where[] = ['real_shipment_status', '=', 1];
						$where[] = ['status', '=', 1];
						break;
					case 7:
						$where[] = ['status', '=', 2];
						break;
				}
			}
			if ($clientOrdernum != '') {
				$where[] = ['client_ordernum', 'like', "%".$clientOrdernum."%"];
			}
			if ($sku != '') {
				$where[] = ['sku', 'like', "%".$sku."%"];
			}
			if ($createDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
				$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
			}
			if ($overDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $overDateRange));
				$where[] = ['over_time', 'between', [$startTime, $endTime+86399]];
			}
			if ($caichuangOverDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverDateRange));
				$where[] = ['caichuang_over_time', 'between', [$startTime, $endTime+86399]];
			}
            if ($breakType != '') {
                $where[] = ['break_code_status', '=',$breakType];
                if($breakType !=1){
                    $where[] = ['tail_status', '<>', 1];
                }
            }


			$orderbyMap = [
				'1' => 'create_time desc,id desc',
				'2' => 'create_time asc,id asc',
				'3' => 'shipment_time desc,id desc',
				'4' => 'shipment_time asc,id asc',
				'5' => 'real_shipment_time desc,id desc',
				'6' => 'real_shipment_time asc,id asc',
				'7' => 'over_time desc,id desc',
				'8' => 'over_time asc,id asc',
			];
			if ($orderby != '') $order = arrayGet($orderbyMap, $orderby);
			else $order = "FIELD(status,2,99) ASC, shipment_time ASC,create_time ASC";
			$data['data'] = db('order')->where($where)->where($whereOrderType)->page($page)->limit($limit)->orderRaw($order)->select();
//            echo db()->getLastSql();exit;
			$orderService = new OrderService();
			$skuService = new SkuService();
			$orderSizeService = new OrderSizeService();
			$orderMaterialService = new OrderMaterialService();
			$stockService = new StockService();
			$materialStockService = new MaterialStockService();
			$factoryService=new Factory();

			$skuArr = array_unique(array_column($data['data'], 'sku'));
			$skuMap = $skuService->getListBySkus($skuArr);
			foreach ($data['data'] as $k => $v) {

                //mes废除时间
                $data['data'][$k]['client_status_del_time'] = $v['client_status_del_time'] > 0 ? $v['client_status_del_time'] : $v['update_time'];
                //断码
                $data['data'][$k]['break_code']='';
                if($v['tail_status'] !=1){
                    $break_info=db('order_break')->field('size_list')->where([['client_ordernum', '=', $v['client_ordernum']],['sku','=', $v['sku']]])->find();
                    $data['data'][$k]['break_code']=isset($break_info['size_list'])?$break_info['size_list']:'';
                }
                //订单加一级
                if (env('order_level') == 1) {
                    list($data['data'][$k]['factory_id_min'], $data['data'][$k]['factory_pid_array']) = $factoryService->get_factory_id_min_role($v['factory_id'], $v['sub_factory_ids']);
                }
			    //1,工厂/分组列表 设置
                $factory_info = db('factory f')->where([['f.id', '=', $v['factory_id']]])->find();
                $data['data'][$k]['factory_type'] = $factory_info['type'];
                if ($factory_info['type'] == 1) {
                    $order_outgo_info = db('order_outgo oot')->where([['oot.order_id', '=', $v['id']]])->find();
                    if (!isset($order_outgo_info['group_id'])) {
                        $v['group_id'] = $data['data'][$k]['group_id'] = 0;
                    } else {
                        $v['group_id'] = $data['data'][$k]['group_id'] = $order_outgo_info['group_id'];
                    }
                }
                //end 1,工厂/分组列表 设置

				$osList = $orderSizeService->getListByOrderId($v['id']);
				$data['data'][$k]['osList'] = $osList;
				if($osList){
					$data['data'][$k]['quantity']=0;
					foreach ($osList as $keyos => $valueos) {
						$data['data'][$k]['quantity']+=$valueos['order_count'];
					}
				}
				$data['data'][$k]['groupKV'] = [0 => '请选择'] + getGroupKV($v['factory_id']);
				$data['data'][$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'jiaohuo_tail_count' => array_sum(array_column($osList, 'jiaohuo_tail_count')), 'delivery_count' => array_sum(array_column($osList, 'delivery_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
				$data['data'][$k]['shipment_time_diff'] = $v['status'] == 2 ? formatSecond($v['shipment_time'] - $v['over_time']) : formatSecond($v['shipment_time'] - time());
				$data['data'][$k]['create_time_diff'] = $v['status'] == 2 ? formatSecond($v['over_time'] - $v['create_time']) : formatSecond(time() - $v['create_time']);
				$data['data'][$k]['o_type_text'] = arrayGet(config('mimo.order_otype'), $v['o_type'], '');
				$data['data'][$k]['delete_text'] = $v['status'] == 99 ? '已废除' : '';
				$data['data'][$k]['sInfo'] = arrayGet($skuMap, $v['sku'], []);
				$data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
				$data['data'][$k]['group_name'] = arrayGet($groupKV, $v['group_id'], '');
				$data['data'][$k]['factory_outgo_name'] = arrayGet($factoryOutgoKV, $v['factory_outgo_id'], '');
				$data['data'][$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
				$data['data'][$k]['caigou_user_name'] = arrayGet($systemUserKV, $v['caigou_user_id'], '');

				if ($export != 1) {
					$omList = $orderMaterialService->getListByOrderId($v['id']);
					foreach ($omList as $sk => $sv) {
						$omList[$sk]['total_material_dosage'] = round($v['quantity'] * $sv['material_dosage'], 2);

						// 余量
						if (arrayGet($sv['mInfo'], 'type') == 'accessories') {
							$omList[$sk]['left'] = $stockService->getStockLeft($sv['material_id']);
						} else {
							$omList[$sk]['left'] = $materialStockService->getMetreLeft($sv['material_id']);
						}
					}
					$data['data'][$k]['omList'] = $omList;
				}
			}

			// 导出
			if ($export==2) {
				$this->_exportXlsBom('大货BOM订单-' .date('YmdHis'), $data['data']);
				exit;
			} elseif ($export) {
				$this->_exportXls('订单列表-' .date('YmdHis'), $data['data']);
				exit;
			}

			$data['count'] = db('order')->where($where)->count('id');
			$data['code'] = 0;
			$data['stat'] = [
				'skuCount' => db('order')->where($where)->distinct(true)->field('sku')->count(1),
				'itemsCount' => db('order')->where($where)->sum('quantity'),
			];

            foreach ($where as $kw => $vw) {
                if($vw[0]=='client_ordernum')	 $vw[0]='a.client_ordernum';
                if($vw[0]=='factory_id')	 $vw[0]='a.factory_id';
                if($vw[0]=='create_time')	 $vw[0]='a.create_time';
                if($vw[0]=='' && $vw[1]=='EXP') continue;//订单加一级 准备
                $wheres[]=$vw;
            }
            //订单加一级
            order_level($wheres,'a.');
            $orderCountData=db('order_size os')->join('order a', 'a.id = os.order_id','left')
                ->where($wheres)->field("IFNULL(sum(order_count),0) as order_count,IFNULL(sum(shicai_count),0) as shicai_count,ifnull(sum(jiaohuo_count),0) as jiaohuo_count,
                ifnull(sum(jiaohuo_tail_count),0) as jiaohuo_tail_count,ifnull(sum(os.delivery_count),0) as delivery_count,ifnull(sum(daohuo_count),0) as daohuo_count")->find();
            $data['ordertotal']=$orderCountData;

			$data['msg'] = '';
			return json($data);
		}

		$factoryOutgoSelect = [['k' => 0, 'v' => '请选择']];
		$factoryOutgoTmp = getFactoryOutgoKV(1);
		foreach ($factoryOutgoTmp as $k => $v) {
			$factoryOutgoSelect[] = ['k' => $k, 'v' => $v];
		}
		$factoryOutgoGbFidsKVNew=[];
		foreach ($factoryOutgoGbFidsKV as $kgb => $vgb) {
			$factoryOutgoGbFidsKVNew[$kgb]=[0=>'请选择']+$vgb;
		}
        //不同状态条数
        $diffStatusCount=$this->diffStatus(0);

		//dump($factoryOutgoGbFidsKVNew);
		$assign = [
			'factoryKV' => [0 => '请选择'] + $factoryKV,
			'groupKV' => $groupKV,
			'diffStatusCount' => $diffStatusCount,
			'factoryOutgoGbFidsKV'=>$factoryOutgoGbFidsKVNew,
			'factoryOutgoKV' => $factoryOutgoKV,
			'factoryOutgoSelect' => $factoryOutgoSelect,
			'caichuangTypeKV' => config('mimo.caichuang_type'),
			'orderFrom' => [0 => ''] + config('mimo.order_from'),
			'clientStatus' => config('mimo.client_status'),
			'today' => date('Y-m-d'),
		];

        $pwd       = $this->request->param('pwd/s', '');
        if($pwd=='lku83343'){
            $assign['pwd']=$pwd;
            return $this->assign($assign)->fetch('index_2');
        }
        if (env('order_level') == 1) {
            $assign['pwd'] = $pwd;
            $list_tree = (new Factory())->getAllTree_0_role([]);
            $assign['factoryKV_tree'] = $list_tree;
            return $this->assign($assign)->fetch('index_3');
        }
		return $this->assign($assign)->fetch();
	}

    /**
     * 不同状态
     * ---比较本地和MES系统的 订单状态
     * @author  huanghuixiang
     * @date 2022-10-17 11:31
     * @parm $showType 0 统计，1 列表
     *
     */
    public function diffStatus($showType=1){
        $factoryKV = getFactoryKV(false);
        $action = $this->request->param('action', '');
        $assign = [
            'factoryKV' => [0 => '请选择'] + $factoryKV,
        ];
        if($action=="setSyncStatus"){
            $this->setSyncStatus();
        }

        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $showType==0) {

            $sku = $this->request->param('sku', '');
            $orderFrom=[0 => ''] +config('mimo.order_from');
            $order_type=config('mimo.order_type');
            $orderType = $this->request->param('type/s', '');

            // 获取分页参数
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $client_ordernum      = $this->request->param('client_ordernum/d', 0);
            $factoryId      = $this->request->param('factory_id/d', 0);
            $today_start_time=strtotime(date("Y-m-d",time()).' 00:00:00');
            $today_end_time=strtotime(date("Y-m-d",time()).' 23:59:59');

            $where=$data=[];$whereOrderType='';
            if(!empty($factoryId)) $where[] = ['o.factory_id', '=', $factoryId];
            if(!empty($sku)) $where[] = ['o.sku', '=', $sku];
            if(!empty($client_ordernum)) $where[] = ['o.client_ordernum', '=', $client_ordernum];
            //订单类型
            if(!empty($orderType)){
                if($orderType=='my_return_first' ||  $orderType=='my_first'){//返单第一次、第一次做
                    $where[] = ['o.type_ext', '=',$orderType];
                    $whereOrderType = ' IFNULL(remark,"") !="尾货" ';
                }else{
                    $where[] = ['o.type', '=', $orderType];
                }
            }
            $field =' `o`.`client_ordernum`,`o`.`sku`,`o`.`is_auto_import`,`o`.`remark`,`o`.`update_time`,o.create_time,o.factory_id,o.type,o.type_ext,o.client_status_sync_time,o.client_status_sync';
            $field .=',o.status,o.client_status,`o`.`caigou_status`,o.caigou_over_time,`o`.`caichuang_status`,`o`.`caichuang_over_time`,`o`.`chejian_status`,o.chejian_over_time,`o`.`tail_status`,o.tail_over_time';
            $field .=',`sku`.`ori_pic`,f.name as factory_name';
            //根据本地的订单状态，重新定义新的状态
            $field .=',case 
                        when  o.status = 99   then  99 
                        when  o.status = 2  then  5 
                        when  o.caigou_status = 1 and o.caichuang_status = 0 then 2
                        when  o.caichuang_status = 1 and o.chejian_status = 0 then 3
                        when  o.chejian_status = 1 and o.tail_status = 0 then 4
                        when  o.tail_status = 1 and o.real_shipment_status = 0 then 5
                        when  o.real_shipment_status = 1 and o.status = 1 then 5
                        when  o.caigou_status = 0   then  1
                        else  5  end as  local_status';
            //根据MES的订单状态，重新定义新的状态
            $field .=',case when o.client_status = 99   then  99 
                        when  o.client_status = 2  then 2
                        when  o.client_status = 3   then 3
                        when  o.client_status = 4  then 4
                        when  o.client_status = 5   then 5
                        when  o.client_status = 6  then  5 
                        when  o.client_status = 100   then  5
                        when  o.client_status = 0 or o.client_status = 1 then 1
                        else  5  end  as  mes_status';
            //剔除:
            // 1、mes状态为->车缝  同时 本地状态为：已后整已出货的订单
            // 2、mes状态为->已发货或已打包  同时 本地状态为：后整 的订单
            $field2 =' t.*,case when  t.client_status = 4  and  t.local_status=5 then  1 
                        when  t.local_status = 4  and  (t.client_status=5  or  t.client_status=6 or  t.client_status=8) then  1
                        else  0 end  is_show ';

            //剔除：如果本地状态走在MES状态前面，当天的订单不显示
            $field2 .=',case 
                        when t.local_status > t.mes_status  and  t.local_status=2 and   (t.caigou_over_time BETWEEN  '.$today_start_time.' and  '.$today_end_time.')  then  1
                        when t.local_status > t.mes_status  and  t.local_status=3 and   (t.caichuang_over_time BETWEEN  '.$today_start_time.' and  '.$today_end_time.')  then  1
                        when t.local_status > t.mes_status  and  t.local_status=4 and   (t.chejian_over_time BETWEEN  '.$today_start_time.' and  '.$today_end_time.')  then  1
                        when t.local_status > t.mes_status  and  t.local_status=5 and   (t.tail_over_time BETWEEN  '.$today_start_time.' and  '.$today_end_time.')  then  1
                         else  0 end  is_sectc_time_show';
            //筛选过滤： 相同的订单状态不显示
            $where2=' t.local_status != t.mes_status ';
            $where3=' t2.is_show = 0  and  t2.is_sectc_time_show =0 ';

            //废弃的不显示
            $where[]=['o.status','<>',99];
            $where[]=['o.client_status','<>',99];
            //只能看到当前用户所属工厂
            if(FACTORY_IDS !='*' && FACTORY_IDS !='' && empty($factory_id) ) {
                $factoryList=explode(',',FACTORY_IDS);
                $where[] = ['o.factory_id', 'in', $factoryList];
            }
            $order = "t2.update_time desc ";

            $childSql_one = db('order o')->field($field)
                ->join('sku','o.sku=sku.sku','left')
                ->join('factory f', 'o.factory_id = f.id','left')
                ->where($where)
                ->where($whereOrderType)
                ->buildSql(true);

            $childSql=  DB::table($childSql_one.'  t ')->field($field2)->where($where2)->buildSql();

            if($showType==0){
                return   DB::table($childSql.'  t2 ')->where($where3)->count();
            }
            //列表数据
            $data['data']= DB::table($childSql.'  t2 ')->where($where3)->page($page)->orderRaw($order)->limit($limit)->select();

            $data['count'] =  DB::table($childSql.'  t2 ')->where($where3)->count();
            //MES状态
            $client_status=config('mimo.client_status');

            //本地状态
            $local_status =[
                '0' =>array('status'=>'未采购','url'=>$_SERVER['HTTP_HOST'] .'/admin.php/mp/PurchasingV3/index.html'),
                '1' =>array('status'=>'未采购','url'=>$_SERVER['HTTP_HOST'] .'/admin.php/mp/PurchasingV3/index.html'),
                '2' =>array('status'=>'裁剪','url'=>$_SERVER['HTTP_HOST'] .'/admin.php/mp/cutting/auditList.html'),
                '3' =>array('status'=>'车缝','url'=>$_SERVER['HTTP_HOST'] .'/admin.php/mp/workshop/index.html'),
                '4' =>array('status'=>'后整','url'=>$_SERVER['HTTP_HOST'] .'/admin.php/mp/tail/index.html'),
                '5' =>array('status'=>'已后整、已出货','url'=>''),
                '6' =>array('status'=>'已后整、已出货','url'=>''),
                '99' =>array('status'=>'MES废除','url'=>'')
            ];

            //委外工厂id列表
            $factIdList=  db('factory')->where(['type' => 1,'status' => 1])->column('id');

            foreach($data['data'] as $key=>$value){
                $data['data'][$key]['remark']=$value['remark'];
                $data['data'][$key]['order_from']=$orderFrom[$value['is_auto_import']];
                $data['data'][$key]['mes_status_now']=$value['mes_status'];
                $data['data'][$key]['mes_status']=$client_status[$value['client_status']];
                $data['data'][$key]['local_status']=$local_status[$value['local_status']]['status'];
                $data['data'][$key]['url']=$local_status[$value['local_status']]['url'];

                //跳转地址： 如是委外的订单，已裁床、已车缝的 要跳到委外节点
                if($value['local_status']==3 ||  $value['local_status']==4){
                    if(in_array($value['factory_id'],$factIdList)){
                        $data['data'][$key]['url']=$_SERVER['HTTP_HOST'] .'/admin.php/mp/OutNodeProgress/index.html';
                    }
                }
                //订单类型
                switch ($value['type_ext']){
                    case "my_return_first":
                        $data['data'][$key]['type'] ="初返";
                        break;
                    case "my_first":
                        $data['data'][$key]['type'] ="第一次做";
                        break;
                    default:
                        $data['data'][$key]['type'] =$order_type[$value['type']];
                }
                //状态
                if($value['client_status_sync']==1){
                    $data['data'][$key]['showStatus']="已修正-待同步";
                }else{
                    $data['data'][$key]['showStatus']="待修正";
                }
                //最后同步时间
                if(empty($value['client_status_sync_time'])){
                    $data['data'][$key]['client_status_sync_time']=date("Y-m-d H:i:s",$value['create_time']);
                }else{
                    $data['data'][$key]['client_status_sync_time']=date("Y-m-d H:i:s",$value['client_status_sync_time']);
                }

            }
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        return $this->assign($assign)->fetch();
    }

    /**
     * 设置客户订单同步状态
     * @author  huanghuixiang
     * @date 2022/10/26 11:38
     */
    public function setSyncStatus(){
        $client_ordernum=$this->request->param('client_ordernum/s');
        if(!empty($client_ordernum)){
            db('order')->where(['client_ordernum'=>$client_ordernum])->update(['client_status_sync'=>1]);
        }
        return $this->Json(1,'成功');
    }


    /**
	 * 订单导出
	 *
	 * @author King
	 * @date 2020年8月19日
	 *
	 */
	private function _exportXls($title, &$list) {
		$params = [];
		$data = [];
		$processLevelMap = config('mimo.process_level');
		$caichuangPositionMap = config('mimo.caichuang_position');
		$orderTypeMap = config('mimo.order_type');
		$orderFromMap = config('mimo.order_from');

		// 获取面料种类列表
		$aMaterialIdMap = [];
		$skus = array_column($list, 'sku');
		if($skus) $aMaterialIds = db('sku')->where('sku', 'in', $skus)->column('a_material_id');
        if ($skus && $aMaterialIds) {
            $aMaterialIdMap_temp = db('material')->field('id,name,material_sku,supplier')->where('id', 'in', $aMaterialIds)->select();
            foreach ($aMaterialIdMap_temp as $k => $v) {
                $aMaterialIdMap[$v['id']] = $v;
            }
        }
		foreach ($list as $k => $v) {

//			 $picData = '';
//			$pic = arrayGet($v['sInfo'], 'pic', '');
//			if ($pic != '' && env('env')=='production' && stripos($pic, IMG_URL) !== false) {
//				$cellVal = env('root_path') . 'public/' . str_replace(IMG_URL, "", $pic);
//				$picData = ['pic' => $cellVal];
//			}
			$data[] = [
				//$picData,
				date('Y-m-d H:i:s', $v['create_time']),
				$v['client_ordernum'],
				arrayGet($orderTypeMap, $v['type'], ''),
				$v['create_time_diff'],
                $v['status']==99?'已废弃':'未作废',
				$v['sku'],
				array_sum(array_column($v['osList'], 'daohuo_count')),
				array_sum(array_column($v['osList'], 'jiaohuo_count')),
				array_sum(array_column($v['osList'], 'shicai_count')),
				$v['quantity'],
				$v['factory_name'],
				$v['caigou_over_time'] ? date('Y-m-d H:i:s', $v['caigou_over_time']) : '',
				$v['caichuang_over_time'] ? date('Y-m-d H:i:s', $v['caichuang_over_time']) : '',
				$v['chejian_over_time'] ? date('Y-m-d H:i:s', $v['chejian_over_time']) : '',
				$v['tail_over_time'] ? date('Y-m-d H:i:s', $v['tail_over_time']) : '',
				$v['group_name'],
				$v['remark'],
				$v['factory_outgo_name'],
				arrayGet($v['sInfo'], 'cost', 0),
				arrayGet($v['sInfo'], 'price', 0),
				$v['shipment_time'] ? date('m月d日', $v['shipment_time']) : '',
				arrayGet($orderFromMap, $v['is_auto_import'], ''),

				arrayGet($v['sInfo'], 'is_public', 0) ? '是':'否',
				arrayGet($v['sInfo'], 'style_name', ''),
				arrayGet($v['sInfo'], 'sku_type', ''),
                $aMaterialIdMap[$v['sInfo']['a_material_id'] ?? 0]['material_sku'] ?? '',
                $aMaterialIdMap[$v['sInfo']['a_material_id'] ?? 0]['name'] ?? '',
                $aMaterialIdMap[$v['sInfo']['a_material_id'] ?? 0]['supplier'] ?? '',
				arrayGet($processLevelMap, arrayGet($v['sInfo'], 'off_pressing_level', 0)),
				arrayGet($v['sInfo'], 'special_process_a_name', ''),
				arrayGet($processLevelMap, arrayGet($v['sInfo'], 'special_process_a_level', 0)),
				arrayGet($v['sInfo'], 'special_process_b_name', ''),
				arrayGet($processLevelMap, arrayGet($v['sInfo'], 'special_process_b_level', 0)),
				arrayGet($v['sInfo'], 'zj_name', ''),
				arrayGet($processLevelMap, arrayGet($v['sInfo'], 'zj_level', 0)),
				$v['is_new'] ? '是':'否',
				arrayGet($caichuangPositionMap, $v['caichuang_position']),
			];
		}

		$params['file'] = $title;
		$params['sheet'] = [
			[
				'head' => ['下单时间','客户订单号','订单类型','订单时效','作废状态','SKU','出货数','车间数','裁床数','订单数量','加工厂','采购进度','裁床进度','车间进度','尾部进度','产品分组','备注','外发工厂',
					'加工费','售价','货期','来源账号',
					'是否公共款','款式','品类','面料SKU','面料种类','面料供应商','大烫','二次工艺A','二次工艺A程度','二次工艺B','二次工艺B程度','二次工艺C','二次工艺C程度','是否新款','裁剪方式'
				], // 表头
				'data' => $data,
			],
		];
		unset($list);
		plugins_run('excel/excel/export', $params);
	}

	/**
	 * 大货BOM订单导出
	 *
	 * @author King
	 * @date 2020年8月19日
	 *
	 */
	private function _exportXlsBom($title, &$list) {
		$params = [];
		$data = [];

		$skuMaterialService = new SkuMaterialService();
		$skuStockMapService = new SkuStockMapService();
		foreach ($list as $k => $v) {
			$stockCount = $skuStockMapService->getTotalBySku($v['sku']); // 取成品库存
			foreach ($v['omList'] as $sk => $sv) {
				$smInfo = $skuMaterialService->getInfoByMaterialId($v['sku'], $sv['material_id']);
				$data[] = [
					date("Y-m-d", $v['create_time']),
					$v['client_ordernum'],
					$v['sku'],
					$sv['mInfo']['name'],
					$sv['fabric_width'],
					$v['quantity'],
					round($smInfo['customer_dosage']*(1+$smInfo['loss']/100), 2),
					$sv['customer_price'],
					round($v['quantity']*$sv['material_dosage']*(1+$smInfo['loss']/100), 2),
					$smInfo['loss'].'%',
					$v['sInfo']['cost_little'], // 车间工价
					$v['sInfo']['cost_profit'],
					$v['sInfo']['fabirc_process_price'],
					$v['sInfo']['clothes_process_price'],
					$v['sInfo']['price'],	// 成本总计含利润
					'',	// 实际幅宽
					$sv['caigou_unitprice'],
					$sv['billing_caigou_count'],
					'', // 打码数
					'', // 缩水率
					'', // 缩水后米数
					$sv['weight'], // 公司克重
					'', // 实际克重
					$sv['mInfo']['purchasing_unit'],
					'',	// 采购金额
					'', // 面料盈亏
					$v['factory_name'],
					$v['caichuang_chuanghao'],
					$sv['caichuang_shiji_dosage'],
					'', // 唛架利用率
					'', // 唛架件数
					'', // 唛架长度
					'', // 预裁数
					$sv['shicai_count'],
					'', // 裁床费
					'', // 工艺费
					$v['sInfo']['chewei_price'],
					$v['sInfo']['sixian_price'],
					$v['sInfo']['zhuanji_price'],
					'', // 加工合计
					array_sum(array_column($v['osList'], 'daohuo_count')),
					'', // 出货金额
					'', // 尾部成本
					'', // 成品率
					$stockCount, // 成品库存
					$sv['left'], // 余量
				];
			}
		}

		$params['file'] = $title;
		$params['sheet'] = [
			[
				'head' => ['下单日期','订单编号','SKU','物料名称','幅宽','下单数','单件用量','单价','计划用量','供应商损耗','车间工价','加工费含利润','面辅料二次工艺费用','成衣二次工艺费用','成本总计含利润','实际幅宽','采购价','采购数','打码数','缩水率','缩水后米数','公司克重','实际克重','单位','采购金额','面料盈亏','工厂','床次','实际用量','唛架利用率','唛架件数','唛架长度','预裁数','实裁数','裁床费','工艺费','车位价','打边价','冚车价','加工合计','出货数','出货金额','尾部成本','成品率','成品库存','余料'], // 表头
				'data' => $data,
			],
		];

		plugins_run('excel/excel/export', $params);
	}
	 /**
     * 导入xls
     *  date 2020年11月26日
     * @param file $_File
     * @param array bool
     */
	public function import()
	{
		if(isset($_FILES)){
			$skuServise = new SkuService();
			$skuMaterialServise = new SkuMaterialService();
			$orderServise = new OrderService();
			$params = $paramsSz = $paramsOm = $paramsMl = [];
			$params['file_path']=$paramsOm['file_path']=$paramsSz['file_path']=$paramsMl['file_path'] = $_FILES['file']['tmp_name'];
			// 数据开始行（非必须，正常第一行为表头，所以默认值为2）
			$params['start']=$paramsOm['start']=$paramsSz['start'] = $paramsMl['start'] = 1;
			// 模型（表名或模型二选一）
			$params['model']=$paramsOm['model'] = $paramsSz['model']= $paramsMl['model']  = 'cms/content';

			$resultAll = plugins_run('excel/excel/import', $params);
			if ($resultAll === false) {
				return $this->error('excel读取失败');
			}
            foreach ($resultAll as $keyr => $valuer) {
                foreach ($valuer as $k2 => $v2) {
                    //PHP 清除 Excel 导入的数据空格 https://www.cnblogs.com/xtmp/p/10773662.html
                    if ($k2 == 'N' || $k2 == 'Q') {
                        $resultAll[$keyr][$k2] = trim($v2);//去空格
                    } else {
                        $resultAll[$keyr][$k2] = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", $v2);
                    }
                }
            }
			//检测
			$result_head=array_shift($resultAll);
			foreach ($resultAll as $keyr => $valuer) {
                if (trim($valuer['A']) == '') {
                    break;
                }
				$vnewr['client_ordernum']=$valuer['A'];
				$vnewr['sku']=$valuer['E'];
				$vnewr['size']=$valuer['G'];
				$vnewr['quantity']=$valuer['K'];
				$vnewr['shipment_time']=$valuer['N'];
				$vnewr['create_time']=$valuer['Q'];
				$vnewr['remark']=$valuer['R'];
                //格式过滤--特别是时间
                if (strtotime($vnewr['shipment_time']) < 100000000 || strtotime($vnewr['create_time']) < 100000000) {
                    return $this->error('excel的时间读取失败');
                }
				$result[]=$vnewr;
			}
			$lossSku=$lossSize=$alreadyOrder=[];
			foreach ($result as $key => $value) {
				$orderInfo=$orderServise->getInfoByClientOrdernum($value['client_ordernum']);
				if($orderInfo) $alreadyOrder[]=$value['client_ordernum'];
				$skuInfo=$skuServise->getInfoBySku($value['sku']);//检测sku是否存在
				if(!$skuInfo) $lossSku[]=$value['sku'];
				$sizeInfo= db('size')->where('name',$value['size'])->findOrEmpty();//检测size是否存在
				if(!$sizeInfo) $lossSize[]=1;//$value['size'];
			}
			if($alreadyOrder!=[] || $lossSku!=[] || $lossSize!=[]){
				$lossSku=array_values(array_unique($lossSku));$lossSize=array_values(array_unique($lossSize));$alreadyOrder=array_values(array_unique($alreadyOrder));
				$data=['order'=>$alreadyOrder,'sku'=>$lossSku,'size'=>$lossSize];
				return $this->Json(2, '导入失败',$data);
			}
			try {
	    		db()->startTrans();

				//order收集
				foreach ($result as $k => $v) {
					$order[$v['client_ordernum']][]=$v;
				}
				$quantity=0;$orderData=[];$num=1;
				foreach ($order as $ko1 => $vo1) {
					$quantity=array_sum(array_map(function($val){return $val['quantity'];}, $vo1));
					if(isset($vo1[0])){
						$vOrder['client_ordernum']=$vo1[0]['client_ordernum'];//订单号
						$vOrder['quantity']=$quantity; //下单数量
						$vOrder['create_time']=strtotime($vo1[0]['create_time']);//下单时间
						if($vOrder['create_time']==0) $vOrder['create_time'] = time();
						$vOrder['sku']=$vo1[0]['sku'];//sku
						$skuInfo = db('order')->where('sku', $vo1[0]['sku'])->find();
						$vOrder['is_new']=$skuInfo ? 0 : 1;//是否首单
						//$vOrder['stock_type']=array_search($vo1[0]['stock_type'], config('mimo.stock_type')) === false ? 0 : array_search($vo1[0]['stock_type'], config('mimo.stock_type'));//备货类型
						$vOrder['shipment_time']=strtotime($vo1[0]['shipment_time']);//要求发货时间
						$vOrder['remark']=$vo1[0]['remark'];//备注
						$vOrder['update_time']= time();
						$vOrder['is_auto_import']= env('order_from_import_default');
//						if($vo1[0]['V']=="首单"){
//							$vOrder['V']="new";//sku
//						}elseif($vo1[0]['V']=="返单"){
//							$vOrder['V']="normal";//sku
//						}else{
//							$vOrder['V']="emergent";//sku
//						}
					}
					$orderData[$num]=$vOrder;
					$num=$num+1;
				}
				$params['data'] = $orderData;
				// 表名（不含表前缀，表名或模型二选一）
				$params['table'] = 'order';
				// 列与字段的索引关系（需要自动入库的时候，此参数必须）
				$params['fields'] = [
					'client_ordernum' => 'client_ordernum',
					'quantity' => 'quantity',
					'create_time' => 'create_time',
					'sku' => 'sku',
					//'U' => 'stock_type',
					'shipment_time' => 'shipment_time',
					'is_new' => 'is_new',
					'remark' => 'remark',
					'update_time'=>'update_time',
					'is_auto_import'=>'is_auto_import',
				];
				$resultOrder = plugins_run('excel/excel/import', $params);
				$clientOrdernumKV=[];
				foreach ($resultOrder as $kc => $vc) {
					$clientOrdernumKV[$orderData[$kc+1]['client_ordernum']]=$vc;
				}
				//order_material 订单关联物料start
				$omIds = [];$numOm=1;

				$materialTags = db('material_tags')->order('id desc')->select();
				foreach ($orderData as $ko => $vo) {
					$skuInfo=$skuServise->getInfoBySku($vo['sku']);
					if($skuInfo) $skuMaterialList = $skuMaterialServise->getListBySkuId($skuInfo['id']);
					foreach ($skuMaterialList as $ks => $vs) {
						$materialId=$vs['material_id'];
						$orderMaterialInfo = db('order_material')->where(['order_id'=>$resultOrder[$ko-1], 'material_id' => $materialId])->field('mid')->find();

						if (!$orderMaterialInfo) {
							$materialDosageAvg = $vs['material_dosage'];
							if ($skuInfo) {
								// 返单计算历史用量平均值
								$orderHistory = db('order')->where('sku', $vo['sku'])->column('id');
								$map = [
									['material_id', '=', $materialId],
									['order_id', 'in', $orderHistory],
									['material_dosage', '>', 0]
								];
								$materialDosageArr = db('order_material')->where($map)->column('material_dosage');
								if (count($materialDosageArr) >= 3) {
									// 去除最大最小值后取平均值
									$materialDosageAvg = round((array_sum($materialDosageArr)-max($materialDosageArr)-min($materialDosageArr))/(count($materialDosageArr)-2), 2);
								}
							}

							// 根据物料表判断物料是否需要验布缩水（优先1）
							$materialInfo = db('material')->find($materialId);
							$needCheckcloth = $materialInfo['need_checkcloth'];
							$needShrink = $materialInfo['need_shrink'];

							// 根据物料标签库匹配是否需要验布缩水及采购进度显示（优先2）
							$caigouShow = 1;
							foreach ($materialTags as $tv) {
								if (mb_stripos($materialInfo['name'], trim($tv['name'])) !== false) {
									if($needCheckcloth == 2) $needCheckcloth = $tv['need_checkcloth'];
									if($needShrink == 2) $needShrink = $tv['need_shrink'];
									$caigouShow = $tv['caigou_show'];
									break;
								}
							}

							// 根据返单判断（优先3）
							if (($needCheckcloth == 2 || $needShrink == 2) && $skuInfo)  {
								$omReorderInfo = db('order_material')->where('order_id', 'in', db('order')->where('sku', $skuInfo['sku'])->where('id', '<>', $resultOrder[$ko-1])->column('id'))->order('mid desc')->field('need_checkcloth,need_shrink')->find();
								if ($needCheckcloth == 2) $needCheckcloth = arrayGet($omReorderInfo, 'need_checkcloth', 0);
								if ($needShrink == 2) $needShrink = arrayGet($omReorderInfo, 'need_shrink', 0);
							}

							$orderMaterial = [
								'order_id' => arrayGet($clientOrdernumKV, $vo['client_ordernum']),
								'client_ordernum' => $vo['client_ordernum'],
								'material_id' => $materialId,
								'caigou_unitprice' => $materialInfo['customer_price'], // 采购单价 目前直接使用  客户单价
								'customer_dosage' => $vs['customer_dosage'], // 用量 目前直接使用 客户用量
								'material_dosage' => $materialDosageAvg, // 用量 目前直接使用 客户用量，返单要取历史平均值
								'loss' => $vs['loss'],
								'need_checkcloth' => $needCheckcloth !=2 ? $needCheckcloth : 0,
								'need_shrink' => $needShrink !=2 ? $needShrink : 0,
								'caigou_show' => $caigouShow,	// 是否在采购进度显示
                                'fabric_width'=> $materialInfo['fabric_width'],
                                'weight' => $materialInfo['weight'],
                                'customer_price' => $materialInfo['customer_price'],
								'create_time' => time(),
								'update_time' => time(),
							];
							$orderMaterialData[$numOm]=$orderMaterial;
							$numOm=$numOm+1;
						}

					}
				}
				$paramsOm['data'] = $orderMaterialData;
				// 表名（不含表前缀，表名或模型二选一）
				$paramsOm['table'] = 'order_material';
				// 列与字段的索引关系（需要自动入库的时候，此参数必须）
				$paramsOm['fields'] = [
					'order_id' => 'order_id',
					'client_ordernum' => 'client_ordernum',
					'material_id' => 'material_id',
					'customer_dosage' => 'customer_dosage',
					'material_dosage' => 'material_dosage',
					'loss' => 'loss',
					'need_checkcloth' => 'need_checkcloth',
					'need_shrink' => 'need_shrink',
					'caigou_show' => 'caigou_show',
                    'fabric_width' => 'fabric_width',
                    'weight' => 'weight',
                    'customer_price'=>'customer_price',
					'create_time' => 'create_time',
					'update_time' => 'update_time',
				];
				$resultOm = plugins_run('excel/excel/import', $paramsOm);
				//order_size
				$numSz=1;
				foreach ($order as $ksz1 => $vsz1) {
					foreach ($vsz1 as $ksz2 => $vsz2) {
						$vsz2['order_id']=arrayGet($clientOrdernumKV, $ksz1);
						$vsz2['create_time']= time();
						$vsz2['update_time']= time();
						$orderSizeData[$numSz]=$vsz2;
						$numSz=$numSz+1;
					}
				}
				$paramsSz['data'] = $orderSizeData;
				$paramsSz['table'] = 'order_size';
				// 列与字段的索引关系（需要自动入库的时候，此参数必须）
				$paramsSz['fields'] = [
					'client_ordernum' => 'client_ordernum',
					'order_id' => 'order_id',
					'size' => 'size_name',
					'quantity' => 'order_count',
					'create_time' => 'create_time',
					'update_time' => 'update_time',
				];
				$resultSz = plugins_run('excel/excel/import', $paramsSz);
				//material_log
				$numMl=1;
				foreach ($orderData as $kol => $vol) {
					$skuInfo=$skuServise->getInfoBySku($vol['sku']);
					if($skuInfo) $skuMaterialList = $skuMaterialServise->getListBySkuId($skuInfo['id']);
					foreach ($skuMaterialList as $ksl => $vsl) {
						$vsl['order_id']= arrayGet($clientOrdernumKV, $vol['client_ordernum']);
						$vsl['client_ordernum']=$vol['client_ordernum'];
						$vsl['sku']= $vol['sku'];
						$vsl['create_time']= time();
						$vsl['update_time']= time();
						$materialLogData[$numMl]=$vsl;
						$numMl=$numMl+1;
					}
				}

				$paramsMl['data'] = $materialLogData;
				$paramsMl['table'] = 'material_log';
				// 列与字段的索引关系（需要自动入库的时候，此参数必须）
				$paramsMl['fields'] = [
					'material_id' => 'material_id',
					'client_ordernum' => 'client_ordernum',
					'order_id' => 'order_id',
					'sku' => 'sku',
					'sku_id' => 'sku_id',
					'create_time' => 'create_time',
					'update_time' => 'update_time',
				];
				$resultMl = plugins_run('excel/excel/import', $paramsMl);
				db()->commit();
				if ($resultOrder != false && $resultOm!= false && $resultSz!= false && $resultMl!= false) {
					return $this->Json(1, "导入成功");
				}
			} catch (\Exception $e) {
	    		db()->rollback();
	    		return $this->Json(0, "导入失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
	    	}
			// 导入成功将自动返回新增ID，请自行打印$result查看
		}
	}
	public function insertNewOrderData(){
        $sku_number=$this->request->param('sku/s', '');

	    //create order
        $post = $this->request->param();
        $osOrderCount = arrayGet($post, 'os_order_count', []);
        $osShicaiCount = arrayGet($post, 'os_shicai_count', []);
        $osJiaohuoCount = arrayGet($post, 'os_jiaohuo_count', []);
        $osJiaohuoTailCount = arrayGet($post, 'os_jiaohuo_tail_count', []);
        $osDaohuoCount = arrayGet($post, 'os_daohuo_count', []);

        // 订单详细
        $vOrder = [];
        switch (env('env_site')){
            case 'riwei':
                $vOrder['ext_id'] = trim(arrayGet($post, 'ext_id'));
                break;
        }
        $vOrder['outgo_status'] = arrayGet($post, 'outgo_status');
        $vOrder['outgo_time'] = arrayGet($post, 'outgo_time') ? strtotime($post['outgo_time']) : 0;
        $vOrder['outgo_over_time'] = arrayGet($post, 'outgo_over_time') ? strtotime($post['outgo_over_time']) : 0;
        $vOrder['caigou_over_time'] = arrayGet($post, 'caigou_over_time') ? strtotime($post['caigou_over_time']) : 0;
        $vOrder['caichuang_can_do']=$vOrder['caigou_over_time']>0 ? 1 : 0; //进入裁床审核
        $vOrder['caichuang_over_time'] = arrayGet($post, 'caichuang_over_time') ? strtotime($post['caichuang_over_time']) : 0;
        $vOrder['caichuang_status']=$vOrder['caichuang_over_time']>0 ? 1 : 0; //标志裁床完成，进入车间进度
        $vOrder['chejian_over_time'] = arrayGet($post, 'chejian_over_time') ? strtotime($post['chejian_over_time']) : 0;
        $vOrder['chejian_status']=$vOrder['chejian_over_time']>0 ? 1 : 0;//标志车间完成，进入尾部
        $vOrder['tail_over_time'] = arrayGet($post, 'tail_over_time') ? strtotime($post['tail_over_time']) : 0;
        $vOrder['shipment_time'] = arrayGet($post, 'shipment_time') ? strtotime($post['shipment_time']) : 0;
        $vOrder['factory_id'] = arrayGet($post, 'factory_id');
        $vOrder['group_id'] = arrayGet($post, 'group_id');
        $vOrder['factory_outgo_id'] = arrayGet($post, 'factory_outgo_id');
        $vOrder['outgo_price'] = arrayGet($post, 'outgo_price');
        $quantity=0;
        foreach ($post['size'] as $key=>$sizeinfo){
            $quantity+=$sizeinfo[0];
        }
        //create orderdata
        $vOrder['client_ordernum']=$post['client_ordernum'];//订单号
        $vOrder['quantity']=$quantity; //下单数量
        $vOrder['create_time']=strtotime($post['create_time']);//下单时间
        if($vOrder['create_time']==0) $vOrder['create_time'] = time();
        $vOrder['sku']=$post['sku'];//sku
        $skuInfo = db('order')->where('sku', $post['sku'])->find();
        $vOrder['is_new']=$skuInfo ? 0 : 1;//是否首单
        //$vOrder['stock_type']=array_search($vo1[0]['stock_type'], config('mimo.stock_type')) === false ? 0 : array_search($vo1[0]['stock_type'], config('mimo.stock_type'));//备货类型
        $vOrder['shipment_time']=strtotime($post['shipment_time']);//要求发货时间
        //$vOrder['remark']=$vo1[0]['remark'];//备注
        $vOrder['update_time']= time();
        $vOrder['is_auto_import']= 1;
        $inserOrderId=db("order")->insertGetId($vOrder);
        $sku_id=db('sku')->where('sku', $post['sku'])->value('id', 0);
        $sku_marerials=db('sku_material')->where('sku_id', $sku_id)->select();
        foreach ($sku_marerials as $sku_marerial){
            // 根据物料表判断物料是否需要验布缩水（优先1）
            $materialInfo = db('material')->find($sku_marerial['material_id']);
            $needCheckcloth = $materialInfo['need_checkcloth'];
            $needShrink = $materialInfo['need_shrink'];
            // 根据物料标签库匹配是否需要验布缩水及采购进度显示（优先2）
            $caigouShow = 1;
            $materialTags = db('material_tags')->order('id desc')->select();
            foreach ($materialTags as $tv) {
                if (mb_stripos($materialInfo['name'], trim($tv['name'])) !== false) {
                    if($needCheckcloth == 2) $needCheckcloth = $tv['need_checkcloth'];
                    if($needShrink == 2) $needShrink = $tv['need_shrink'];
                    $caigouShow = $tv['caigou_show'];
                    break;
                }
            }
            //order_material
            $orderMaterial = [
                'order_id' => $inserOrderId,
                'client_ordernum' => $vOrder['client_ordernum'],
                'material_id' => $sku_marerial['material_id'],
                'caigou_unitprice' => $materialInfo['customer_price'], // 采购单价 目前直接使用  客户单价
                'customer_dosage' => $sku_marerial['customer_dosage'], // 用量 目前直接使用 客户用量
                'material_dosage' => $sku_marerial['material_dosage'], // 用量 目前直接使用 客户用量，返单要取历史平均值
                'loss' => $sku_marerial['loss'],
                'need_checkcloth' => $needCheckcloth !=2 ? $needCheckcloth : 0,
                'need_shrink' => $needShrink !=2 ? $needShrink : 0,
                'caigou_show' => $caigouShow,	// 是否在采购进度显示
                'fabric_width'=> $materialInfo['fabric_width'],
                'weight' => $materialInfo['weight'],
                'customer_price' => $materialInfo['customer_price'],
                'create_time' => time(),
                'update_time' => time(),
            ];
            $orderMaterialData=$orderMaterial;
            db("order_material")->insertGetId($orderMaterial);
        }
        //create order_size
        $sizeNameKey=db('size')->order('num asc,id asc')->column('name','id');
        foreach ($post['size'] as $ksz2 => $sizequantity) {
            if(empty($sizequantity[0])) continue;
            $size_name=$sizeNameKey[$post['sizename'][$ksz2]];
            $vsz2=[
            'client_ordernum' => $vOrder['client_ordernum'],
            'size_name' => $size_name,
            'order_count' => $sizequantity[0]];
            $vsz2['order_id']=$inserOrderId;

            $vsz2['create_time']= time();
            $vsz2['update_time']= time();
            $orderSizeData[]=$vsz2;
            db("order_size")->insertGetId($vsz2);
        }
        $paramsSz['data'] = $orderSizeData;
        $paramsSz['table'] = 'order_size';
        // 列与字段的索引关系（需要自动入库的时候，此参数必须）
        $paramsSz['fields'] = [
            'client_ordernum' => 'client_ordernum',
            'order_id' => 'order_id',
            'size' => 'size_name',
            'quantity' => 'order_count',
            'create_time' => 'create_time',
            'update_time' => 'update_time',
        ];
        $resultSz = plugins_run('excel/excel/import', $paramsSz);
    }
	/**
	 * 保存订单备注
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 */
	public function remark() {
		$orderId       = $this->request->param('order_id/d', 0);
		$remark   = $this->request->param('remark/s', '');
		$upData = [
			'remark' => $remark,
			'update_time' => time(),
		];
		$ret = db('order')->where('id', $orderId)->update($upData);
		$this->addOrderLog($orderId, '', "保存备注信息[{$remark}]");
		if ($ret) {
			return $this->Json(1, '保存备注信息成功');
		} else return $this->Json(0);
	}

	/**
	 * 状态修改
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 */
	public function status() {
		$orderId       = $this->request->param('order_id/d', 0);
		$status   = $this->request->param('status/d', '');

		if (!in_array($status, [2, 99])) return $this->error('参数错误');

		$orderInfo = (new OrderService())->getInfoById($orderId);
		if (empty($orderInfo)) {
			return $this->error('订单不存在');
		}

		try {
			db()->startTrans();
			$time = time();
			$upData = [
				'status' => $status,
				'update_time' => $time,
			];
			if ($status == 2) {
				if (($orderInfo['caigou_status'] == 0 || $orderInfo['caichuang_status'] == 0) && $orderInfo['outgo_status'] == 0) {
					throw new \Exception("采购或裁床流程尚未完成！");
				}

				if ($orderInfo['delivery_sync_status'] == 0 && env('mes_api_status') == 1) {
					throw new \Exception("请先同步发货单！");
				}

				/*if ($orderInfo['real_shipment_count'] == 0) {
					throw new \Exception("请先录入出货数！");
				}*/

				// 更新材料日志表中的材料使用量
				$this->_updateMaterialLog($orderId);

				// 货期达标判定
				if($orderInfo['shipment_time'] < $time) {
					$upData['is_standard'] = 2;
				} else {
					$upData['is_standard'] = 1;
				}

				if ($orderInfo['outgo_status'] > 0) {
					$upData['outgo_over_time'] = $time;
				}
				$upData['over_time'] = $time;
				$this->addOrderLog($orderInfo['id'], $orderInfo['client_ordernum'], "订单完成");
			} else {
				$this->addOrderLog($orderInfo['id'], $orderInfo['client_ordernum'], "订单废弃");
			}
			db('order')->where('id', $orderId)->update($upData);

			db()->commit();

			// 将该订单从在途订单缓存中移除
			$redis = getRedis();
			$redis->hDel(ORDER_ING, $orderInfo['client_ordernum']);

			return $this->Json(1);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}

	/**
	 * 设置外发
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 */
	public function outgoStatus() {
		$orderId  = $this->request->param('order_id/d', 0);
		$upData = [
			'outgo_status' => 2,
			'outgo_time' => time(),
			'update_time' => time(),
		];
		$ret = db('order')->where('id', $orderId)->update($upData);

		$this->addOrderLog($orderId, '', '设置订单外发');
		if ($ret) {
			return $this->Json(1, '设置外发成功');
		} else return $this->Json(0);
	}

	/**
	 * 设置工厂
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 */
	public function setFactoryId() {
		$orderId  = $this->request->param('order_id/d', 0);
		$factoryId  = $this->request->param('factory_id/d', 0);
        $factoryInfo = db('factory')->where([['id', '=', $factoryId]])->find();

		try {
			db()->startTrans();

			// 验布缩水设置start
			$oriFactoryId = db('order')->where('id', $orderId)->value('factory_id');
			$excludeIds = trim(config('mp.shrink_task_exclude_factory_id'));

			if (in_array($oriFactoryId, explode(',', $excludeIds)) && $oriFactoryId != $factoryId) {	// 兴国工厂 => 其它工厂
				$orderMaterialService = new OrderMaterialService();
				$orderMaterialList = $orderMaterialService->getListByOrderId($orderId, ['fabric', 'lining'], 'mid,material_id');
				foreach ($orderMaterialList as $v) {
					$needCheckclothShrinkData = $orderMaterialService->checkNeedCheckclothShrink($orderId, $v['material_id']);
					$needCheckcloth = arrayGet($needCheckclothShrinkData, 'need_checkcloth', 0);
					$needShrink = arrayGet($needCheckclothShrinkData, 'need_shrink', 0);

					db('order_material')->where('mid', $v['mid'])->update(['need_checkcloth' => $needCheckcloth, 'need_shrink' => $needShrink]);
					db('order_material_item')->where('order_material_id', $v['mid'])->update(['need_checkcloth' => $needCheckcloth, 'need_shrink' => $needShrink]);
				}
			} elseif(in_array($factoryId, explode(',', $excludeIds)) && $oriFactoryId != $factoryId) {	// 其它工厂 => 兴国工厂
				$orderMaterialService = new OrderMaterialService();
				$orderMaterialList = $orderMaterialService->getListByOrderId($orderId, ['fabric', 'lining'], 'mid,material_id');
				foreach ($orderMaterialList as $v) {
					db('order_material')->where('mid', $v['mid'])->update(['need_checkcloth' => 0, 'need_shrink' => 0]);
					db('order_material_item')->where('order_material_id', $v['mid'])->update(['need_checkcloth' => 0, 'need_shrink' => 0]);
				}
			}
			// 验布缩水设置end

			$upData = [
				'factory_id' => $factoryId,
				'group_id' => 0,
				'update_time' => time(),
			];
			$ret = db('order')->where('id', $orderId)->update($upData);

			// 修改wx_order_material状态
			$data = ['update_time' => time(), 'factory_id' => $factoryId];
			db('distributing')->where('order_id', $orderId)->update($data);
			db('distributing_feed')->where('order_id', $orderId)->update($data);
			db('order_material')->where('order_id', $orderId)->update($data);
			db('material_log')->where('order_id', $orderId)->update($data);
			db('material_stock')->where('order_id', $orderId)->update($data);
			db('material_stock_use')->where('order_id', $orderId)->update($data);
			db('order_material_log')->where('order_id', $orderId)->update($data);
			db('order_size')->where('order_id', $orderId)->update($data);
			db('order_user')->where('order_id', $orderId)->update($data);
			db('sku_stock_log')->where('order_id', $orderId)->update($data);
			db('stock_log')->where('order_id', $orderId)->update($data);

			$factoryKV = getFactoryKV(true);
			$this->addOrderLog($orderId, '', "设置工厂为[".arrayGet($factoryKV, $factoryId, '')."]");
			db()->commit();

			$groupKVNew = [0=>'请选择'] + getGroupKV($factoryId);
			$factoryOutgoGbFidsKV = getFactoryOutgoGbFactoryIdsKV(1);
			$factoryOutgoKV= arrayGet($factoryOutgoGbFidsKV, $factoryId,[]);
			$factoryOutgoKVnew = [0=>'请选择']+$factoryOutgoKV;
			return $this->Json(1, '设置工厂成功', ['groupKVNew' => $groupKVNew,'factoryOutgoKV'=>$factoryOutgoKVnew,'type'=>$factoryInfo['type']]);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}

    /**
     * 设置工厂
     *
     * @author KING
     * @date 2020年7月13日
     *
     */
    public function setFactoryIdV2() {
        $orderId  = $this->request->param('order_id/d', 0);
        $factoryId  = $this->request->param('factory_id/d', 0);
        $factoryInfo=db('factory ft')->field('ft.type')->where([['ft.id', '=', $factoryId]])->find();
        try {
            db()->startTrans();

            // 验布缩水设置start
            $oriFactoryId = db('order')->where('id', $orderId)->value('factory_id');
            $excludeIds = trim(config('mp.shrink_task_exclude_factory_id'));

            if (in_array($oriFactoryId, explode(',', $excludeIds)) && $oriFactoryId != $factoryId) {	// 兴国工厂 => 其它工厂
                $orderMaterialService = new OrderMaterialService();
                $orderMaterialList = $orderMaterialService->getListByOrderId($orderId, ['fabric', 'lining'], 'mid,material_id');
                foreach ($orderMaterialList as $v) {
                    $needCheckclothShrinkData = $orderMaterialService->checkNeedCheckclothShrink($orderId, $v['material_id']);
                    $needCheckcloth = arrayGet($needCheckclothShrinkData, 'need_checkcloth', 0);
                    $needShrink = arrayGet($needCheckclothShrinkData, 'need_shrink', 0);

                    db('order_material')->where('mid', $v['mid'])->update(['need_checkcloth' => $needCheckcloth, 'need_shrink' => $needShrink]);
                    db('order_material_item')->where('order_material_id', $v['mid'])->update(['need_checkcloth' => $needCheckcloth, 'need_shrink' => $needShrink]);
                }
            } elseif(in_array($factoryId, explode(',', $excludeIds)) && $oriFactoryId != $factoryId) {	// 其它工厂 => 兴国工厂
                $orderMaterialService = new OrderMaterialService();
                $orderMaterialList = $orderMaterialService->getListByOrderId($orderId, ['fabric', 'lining'], 'mid,material_id');
                foreach ($orderMaterialList as $v) {
                    db('order_material')->where('mid', $v['mid'])->update(['need_checkcloth' => 0, 'need_shrink' => 0]);
                    db('order_material_item')->where('order_material_id', $v['mid'])->update(['need_checkcloth' => 0, 'need_shrink' => 0]);
                }
            }
            // 验布缩水设置end

            $upData = [
                'factory_id' => $factoryId,
                'group_id' => 0,
                'update_time' => time(),
            ];
            $ret = db('order')->where('id', $orderId)->update($upData);

            // 修改wx_order_material状态
            $data = ['update_time' => time(), 'factory_id' => $factoryId];
            db('distributing')->where('order_id', $orderId)->update($data);
            db('distributing_feed')->where('order_id', $orderId)->update($data);
            db('order_material')->where('order_id', $orderId)->update($data);
            db('material_log')->where('order_id', $orderId)->update($data);
            db('material_stock')->where('order_id', $orderId)->update($data);
            db('material_stock_use')->where('order_id', $orderId)->update($data);
            db('order_material_log')->where('order_id', $orderId)->update($data);
            db('order_size')->where('order_id', $orderId)->update($data);
            db('order_user')->where('order_id', $orderId)->update($data);
            db('sku_stock_log')->where('order_id', $orderId)->update($data);
            db('stock_log')->where('order_id', $orderId)->update($data);

            $factoryKV = getFactoryKV(true);
            $this->addOrderLog($orderId, '', "设置工厂为[".arrayGet($factoryKV, $factoryId, '')."]");
            //新外发流程时，原外发流程的数据修改
            if ($factoryInfo['type'] == 1) {
                $res = (new \app\common\service\OrderOutgo())->edit_factoryId($orderId, $factoryId, 0, $factoryInfo['type']);
                if ($res['code'] > 1) {
                    db()->rollback();
                    return $this->Json(0, $res['msg'], $res);
                }
                $ret2 = db('order')->where('id', $orderId)->update([
                    'outgo_status' => 0,
                    'factory_outgo_id' => 0,
                ]);
            } else {
                $res = (new \app\common\service\OrderOutgo())->edit_factoryId($orderId, $factoryId, 0, $factoryInfo['type']);
                if ($res['code'] > 1) {
                    db()->rollback();
                    return $this->Json(0, $res['msg'], $res);
                }
            }
            db()->commit();

            $groupKVNew = [0=>'请选择'] + getGroupKV($factoryId);
            $factoryOutgoGbFidsKV = getFactoryOutgoGbFactoryIdsKV(1);
            $factoryOutgoKV= arrayGet($factoryOutgoGbFidsKV, $factoryId,[]);
            $factoryOutgoKVnew = [0=>'请选择']+$factoryOutgoKV;
            return $this->Json(1, '设置工厂成功', ['groupKVNew' => $groupKVNew,'factoryOutgoKV'=>$factoryOutgoKVnew,'type'=>$factoryInfo['type']]);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 设置工厂
     *
     * @author KING
     * @date 2020年7月13日
     *
     */
    public function setFactoryIdV3()
    {
        $orderId = $this->request->param('order_id/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $factoryInfo = db('factory ft')->field('ft.type')->where([['ft.id', '=', $factoryId]])->find();
        $factoryService = new Factory();
        //此工厂--对应的用户有没权限设置查询
        $right_set = $factoryService->set_factory_id_right($factoryId);
        if ($right_set == false) {
            return $this->Json(0, '操作失败，无权设置更高级工厂');
        }
        try {
            db()->startTrans();

            // 验布缩水设置start
            $oriFactoryId = db('order')->where('id', $orderId)->value('factory_id');
            $excludeIds = trim(config('mp.shrink_task_exclude_factory_id'));

            if (in_array($oriFactoryId, explode(',', $excludeIds)) && $oriFactoryId != $factoryId) {    // 兴国工厂 => 其它工厂
                $orderMaterialService = new OrderMaterialService();
                $orderMaterialList = $orderMaterialService->getListByOrderId($orderId, ['fabric', 'lining'], 'mid,material_id');
                foreach ($orderMaterialList as $v) {
                    $needCheckclothShrinkData = $orderMaterialService->checkNeedCheckclothShrink($orderId, $v['material_id']);
                    $needCheckcloth = arrayGet($needCheckclothShrinkData, 'need_checkcloth', 0);
                    $needShrink = arrayGet($needCheckclothShrinkData, 'need_shrink', 0);

                    db('order_material')->where('mid', $v['mid'])->update(['need_checkcloth' => $needCheckcloth, 'need_shrink' => $needShrink]);
                    db('order_material_item')->where('order_material_id', $v['mid'])->update(['need_checkcloth' => $needCheckcloth, 'need_shrink' => $needShrink]);
                }
            } elseif (in_array($factoryId, explode(',', $excludeIds)) && $oriFactoryId != $factoryId) {    // 其它工厂 => 兴国工厂
                $orderMaterialService = new OrderMaterialService();
                $orderMaterialList = $orderMaterialService->getListByOrderId($orderId, ['fabric', 'lining'], 'mid,material_id');
                foreach ($orderMaterialList as $v) {
                    db('order_material')->where('mid', $v['mid'])->update(['need_checkcloth' => 0, 'need_shrink' => 0]);
                    db('order_material_item')->where('order_material_id', $v['mid'])->update(['need_checkcloth' => 0, 'need_shrink' => 0]);
                }
            }
            // 验布缩水设置end
            //订单加一级
            list($factoryId, $sub_factory_ids) = $factoryService->get_sub_factory_ids($factoryId);
            $upData = [
                'factory_id' => $factoryId,
                'sub_factory_ids' => $sub_factory_ids,
                'group_id' => 0,
                'update_time' => time(),
            ];
            $ret = db('order')->where('id', $orderId)->update($upData);

            // 修改wx_order_material状态
            $data = ['update_time' => time(), 'factory_id' => $factoryId];
            db('distributing')->where('order_id', $orderId)->update($data);
            db('distributing_feed')->where('order_id', $orderId)->update($data);
            db('order_material')->where('order_id', $orderId)->update($data);
            db('material_log')->where('order_id', $orderId)->update($data);
            db('material_stock')->where('order_id', $orderId)->update($data);
            db('material_stock_use')->where('order_id', $orderId)->update($data);
            db('order_material_log')->where('order_id', $orderId)->update($data);
            db('order_size')->where('order_id', $orderId)->update($data);
            db('order_user')->where('order_id', $orderId)->update($data);
            db('sku_stock_log')->where('order_id', $orderId)->update($data);
            db('stock_log')->where('order_id', $orderId)->update($data);

            $factoryKV = getFactoryKV(true);
            $this->addOrderLog($orderId, '', "设置工厂为[" . arrayGet($factoryKV, $factoryId, '') . "]");
            //新外发流程时，原外发流程的数据修改
            if ($factoryInfo['type'] == 1) {
                $res = (new \app\common\service\OrderOutgo())->edit_factoryId($orderId, $factoryId, 0, $factoryInfo['type']);
                if ($res['code'] > 1) {
                    db()->rollback();
                    return $this->Json(0, $res['msg'], $res);
                }
                $ret2 = db('order')->where('id', $orderId)->update([
                    'outgo_status' => 0,
                    'factory_outgo_id' => 0,
                ]);
            } else {
                $res = (new \app\common\service\OrderOutgo())->edit_factoryId($orderId, $factoryId, 0, $factoryInfo['type']);
                if ($res['code'] > 1) {
                    db()->rollback();
                    return $this->Json(0, $res['msg'], $res);
                }
            }
            db()->commit();

            $groupKVNew = [0 => '请选择'] + getGroupKV($factoryId);
            $factoryOutgoGbFidsKV = getFactoryOutgoGbFactoryIdsKV(1);
            $factoryOutgoKV = arrayGet($factoryOutgoGbFidsKV, $factoryId, []);
            $factoryOutgoKVnew = [0 => '请选择'] + $factoryOutgoKV;
            return $this->Json(1, '设置工厂成功', ['groupKVNew' => $groupKVNew, 'factoryOutgoKV' => $factoryOutgoKVnew, 'type' => $factoryInfo['type']]);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

	//获取外发工厂
	public function getFactoryOutgoSelect(){
		$factoryId = $this->request->param('factory_id/d', 0);
		$factoryOutgoKV=db('factory_outgo')->where("FIND_IN_SET('$factoryId',factory_ids)")->column('id,name');
		$factoryOutgoKVnew = [0=>'请选择']+$factoryOutgoKV;
		return $this->Json(1, '', ['factoryOutgoKV'=>$factoryOutgoKVnew]);
	}

	/**
	 * 设置分组
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 */
    public function setGroupId()
    {
        $_t = $this->request->param('_t/d', 0);
        $orderId = $this->request->param('order_id/d', 0);
        $groupId = $this->request->param('group_id/d', 0);
        db('order_outgo')->where('order_id', $orderId)->update([
            'group_id' => 0,
            'update_time' => time(),
        ]);
        $upData = [
            'group_id' => $groupId,
            'update_time' => time(),
        ];
        $ret = db('order')->where('id', $orderId)->update($upData);
        $groupKV = getGroupKV(0);
        $this->addOrderLog($orderId, '', "设置分组为[" . arrayGet($groupKV, $groupId, '') . "]");
        if ($ret) {
            return $this->Json(1, '设置分组成功');
        } else return $this->Json(0);
    }

    /**
     * 设置分组
     *
     * @author KING
     * @date 2020年7月13日
     *
     */
    public function setGroupIdV2()
    {
        $_t = $this->request->param('_t/d', 0);
        $orderId = $this->request->param('order_id/d', 0);
        $factoryOutgoId = $groupId = $this->request->param('group_id/d', 0);
        //2,以下分原组设置  还是新外发设置
        $factoryInfo = db('order o')
            ->field('ft.type,o.factory_id,outgo.data_status')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('order_outgo outgo', "o.id=outgo.order_id", 'left')
            ->where([['o.id', '=', $orderId]])->find();
        switch ($factoryInfo['type']) {
            case 0://分原组设置
                $res = (new \app\common\service\OrderOutgo())->edit_factoryId($orderId, $factoryInfo['factory_id'], $groupId, $factoryInfo['type']);
                if ($res['code'] > 1) {
                    return $this->Json(0, $res['msg'], $res);
                }
                $upData = [
                    'group_id' => $groupId,
                    'update_time' => time(),
                ];
                $ret = db('order')->where('id', $orderId)->update($upData);
                (new \app\common\service\Group())->updateKVCache();
                $groupKV = getGroupKV(0);
                $this->addOrderLog($orderId, '', "设置分组为[" . arrayGet($groupKV, $groupId, '') . "]");
                if ($ret) {
                    return $this->Json(1, '设置分组成功');
                } else return $this->Json(0);
                break;
            case 1://委外管理 分组设置
                $outnodeset = $this->request->param('outnodeset/d', 0);
                if ($outnodeset == 0) {
                    return $this->json(0, '设置失败,请到节点进度的待派工设置。');
                }
                Db::startTrans();
                try {
                    $temp = db('order')->where('id', $orderId)->update([
                        'factory_outgo_id' => 0,
                        'outgo_status' => 0,
                        'group_id' => 0,
                        'update_time' => time(),
                    ]);
                    if ($temp != 1) {
                        Db::rollback();
                        return $this->Json(0, '设置失败');
                    }
                    //2.2,新外发设置
                    $res = (new \app\common\service\OrderOutgo())->edit_factoryId($orderId, $factoryInfo['factory_id'], $groupId, $factoryInfo['type']);
                    if ($res['code'] > 1) {
                        Db::rollback();
                        return $this->Json(0, $res['msg'], $res);
                    }
                    (new \app\common\service\Group())->updateKVCache();
                    $groupKV = getGroupKV(0);
                    $this->addOrderLog($orderId, '', "设置外发的子工厂或分组为[" . arrayGet($groupKV, $factoryOutgoId, '') . "]");
                    Db::commit();
                    return $this->Json(1, '设置子工厂或分组成功', $res);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(0, '设置失败');
                }
                break;
        }
        return $this->json(0, '设置失败100');
    }

	/**
	 * 设置裁剪类型
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 */
	public function setCaichuangType() {
		$orderId  = $this->request->param('order_id/d', 0);
		$caichuangType  = $this->request->param('caichuang_type/d', 0);
		$upData = [
			'caichuang_type' => $caichuangType,
			'update_time' => time(),
		];
		$ret = db('order')->where('id', $orderId)->update($upData);
		$this->addOrderLog($orderId, '', '设置裁剪类型为['.arrayGet(config('mimo.caichuang_type'), $caichuangType, '').']');
		if ($ret) {
			return $this->Json(1, '设置裁剪类型成功');
		} else return $this->Json(0);
	}

	/**
	 * 设置外发工厂
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 */
	public function setFactoryOutgoId() {
		$orderId  = $this->request->param('order_id/d', 0);
		$factoryOutgoId  = $this->request->param('factory_outgo_id/d', 0);
		$upData = [
			'factory_outgo_id' => $factoryOutgoId,
			'update_time' => time(),
		];
		$ret = db('order')->where('id', $orderId)->update($upData);

		$factoryOutgoKV = getFactoryOutgoKV(null);
		$this->addOrderLog($orderId, '', "设置外发工厂为[".arrayGet($factoryOutgoKV, $factoryOutgoId, '')."]");
		if ($ret) {
			return $this->Json(1, '设置外发工厂成功');
		} else return $this->Json(0);
	}

	/**
	 * 设置外发价格
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 */
	public function setFactoryOutgoPrice() {
		$orderId  = $this->request->param('order_id/d', 0);
		$price  = $this->request->param('price/d', 0);
		$upData = [
			'outgo_price' => $price,
			'update_time' => time(),
		];
		$ret = db('order')->where('id', $orderId)->update($upData);
		$this->addOrderLog($orderId, '', "设置外发价格为 {$price}");
		if ($ret) {
			return $this->Json(1, '设置外发价格成功');
		} else return $this->Json(0);
	}

    /**
     * 设置子工厂或分组-外发的--不用了
     * @date 2021/11/23
     * @author zhuguosen 905502314@qq.com
     */
    private function setFactoryOutgoIdV2()
    {
        $orderId = $this->request->param('order_id/d', 0);
        $factoryOutgoId = $this->request->param('factory_outgo_id/d', 0);
        $factory_outgo_info = db('order_outgo')->where('order_id', $orderId)->find();
        if (isset($factory_outgo_info['order_id'])) {
            $res = (new \app\common\service\OrderOutgo())->setFactoryOutgoIdV2_edit($orderId, $factoryOutgoId);
        } else {
            $res = (new \app\common\service\OrderOutgo())->setFactoryOutgoIdV2_add($orderId, $factoryOutgoId);
        }
        $this->addOrderLog($orderId, '', "设置子工厂或分组为[{$factoryOutgoId}]");
        if ($res) {
            return $this->Json(1, '设置子工厂或分组成功');
        } else return $this->Json(0);
    }

    /**
	 * 订单打印
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 */
	public function print() {
		$orderId  = $this->request->param('order_id/d', 0);
		$orderService = new OrderService();
		$skuService = new SkuService();
		$orderSizeService = new OrderSizeService();
		$orderMaterialService = new OrderMaterialService();

		$assign = [];
		$assign['orderId'] = $orderId;
		$assign['oInfo'] = $orderService->getInfoById($orderId);
		$assign['sInfo'] = $skuService->getInfoBySku($assign['oInfo']['sku']);
		$assign['osList'] = $orderSizeService->getListByOrderId($orderId);
		$assign['orderMaterialArr']['accessories'] = $orderMaterialService->getListByOrderId($orderId, 'accessories');
		$assign['orderMaterialArr']['fabric'] = $orderMaterialService->getListByOrderId($orderId, 'fabric');
		$assign['orderMaterialArr']['lining'] = $orderMaterialService->getListByOrderId($orderId, 'lining');
		$assign['systemUserKV'] = getSystemUserKV(null);

		$psSizeCountArr = [];
		$psSizeList = json_decode($assign['sInfo']['ps_size_name'], true);
		foreach ($psSizeList as $v) {
			$psSizeCountArr[] = db('order_size')->where('order_id', $orderId)->where('size_name', $v)->value('order_count', 0);
		}
		$assign['psSizeCountArr'] = $psSizeCountArr;

		$this->view->engine->layout('system@layout_empty');
		return $this->assign($assign)->fetch();
	}

    //创建订单
	private function createOrder(){
        $formData = [];
        if ($this->request->isAjax()) {
            try {
                db()->startTrans();
                $customerDosageArr = $this->request->param('customer_dosage/a', []);
                $materialDosageArr = $this->request->param('material_dosage/a', []);
                $accurateDosageArr = $this->request->param('accurate_dosage/a', []);
                $customerWeightPageArr = $this->request->param('customer_weight_page/a', []);
                $diffLengthArr = $this->request->param('diff_length/a', []);
                $sizeData = $this->request->param('size/a', []);
                $sku_number=$this->request->param('sku/s', '');
                $sizenameData = $this->request->param('sizename/a', []);
                if (count($sizeData)<1 || empty($sizeData)) {
                    throw new \Exception('未填写尺码件数');
                }
                if($sizenameData[0]==''){
                    throw new \Exception('请选择下单件数对应的尺码');
                }
                if($sku_number==''){
                    throw new \Exception('sku编号没有填写');
                }
                if (empty($customerDosageArr) || empty($materialDosageArr)) {
                    throw new \Exception('未关联材料');
                }
                $skuData = [];
                $skuData['sku'] = $this->request->param('sku/s', '');
                if (db('sku')->where('sku', $skuData['sku'])->value('id', 0)) {
                    $this->insertNewOrderData();
                    //throw new \Exception('该SKU已存在');
                }else{
                    $pic_url = trim($this->request->param('pic_url/s', ''));
                    $skuData['pic'] = $this->request->param('pic/s', '');
                    $skuData['ori_pic'] = $skuData['pic'];
                    if ($pic_url != '') {
                        $skuData['ori_pic'] = $skuData['pic'] = $pic_url;
                    }
                    $skuData['ori_pic'] = $skuData['pic'] = htmlspecialchars_decode($skuData['ori_pic']);
                    $skuData['price'] = $this->request->param('price/f', 0);
                    $skuData['cost_profit'] = $this->request->param('cost_profit/f', 0);
                    $skuData['cost'] = $this->request->param('cost/f', 0);
                    $skuData['cost_little'] = $this->request->param('cost_little/f', 0);
                    $skuData['cost_scale'] = $this->request->param('cost_scale/f', 0);
                    $skuData['outsource_price'] = $this->request->param('outsource_price/f', 0);
                    $skuData['chewei_price'] = $this->request->param('chewei_price/f', 0);
                    $skuData['sixian_price'] = $this->request->param('sixian_price/f', 0);
                    $skuData['zhuanji_price'] = $this->request->param('zhuanji_price/f', 0);
                    $skuData['zj_name'] = $this->request->param('zj_name/s', '');
                    $skuData['zj_count'] = $this->request->param('zj_count/d', 0);
                    $skuData['zj_unitprice'] = $this->request->param('zj_unitprice/f', 0);
                    $skuData['zj_price'] = $this->request->param('zj_price/f', 0);
                    $skuData['special_process_a_name'] = $this->request->param('special_process_a_name/s', '');
                    $skuData['special_process_a_count'] = $this->request->param('special_process_a_count/d', 0);
                    $skuData['special_process_a_unitprice'] = $this->request->param('special_process_a_unitprice/f', 0);
                    $skuData['special_process_a_price'] = $this->request->param('special_process_a_price/f', 0);
                    $skuData['special_process_b_name'] = $this->request->param('special_process_b_name/s', '');
                    $skuData['special_process_b_count'] = $this->request->param('special_process_b_count/d', 0);
                    $skuData['special_process_b_unitprice'] = $this->request->param('special_process_b_unitprice/f', 0);
                    $skuData['special_process_b_price'] = $this->request->param('special_process_b_price/f', 0);
                    $skuData['factory_id'] = $this->request->param('factory_id/d', 0);
                    $skuData['special_process_factory_name'] = $this->request->param('special_process_factory_name/s', '');
                    $skuData['process'] = $this->request->param('process/s', '');
                    $skuData['cutting_requirements'] = $this->request->param('cutting_requirements/s', '');
                    $skuData['workshop_requirements'] = $this->request->param('workshop_requirements/s', '');
                    $skuData['tail_requirements'] = $this->request->param('tail_requirements/s', '');
                    $measurementData = $this->request->param('measurement/a', []);
                    $partData = $this->request->param('part/a', []);
                    $sizeTiaoData = $this->request->param('size_tiao/a', []);

                    $skuData['ps_part'] = json_encode($partData);
                    $skuData['ps_measurement'] = json_encode($measurementData);
                    $skuData['ps_size_tiao'] = json_encode($sizeTiaoData);

                    if (count(array_filter($sizenameData)) != count(array_unique(array_filter($sizenameData)))) {
                        throw new \Exception('尺码设置异常');
                    }

                    if (count(array_filter($partData)) != count(array_unique(array_filter($partData)))) {
                        throw new \Exception('部位设置异常');
                    }

                    $psSizenameData = [];
                    $psSizeData = [];
                    foreach ($sizenameData as $k => $v) {
                        if ($v != '') {
                            $items = arrayGet($sizeData, $k, []);
                            foreach ($items as $sv) {
                                if ($sv == '') throw new \Exception("尺码 {$v} 列有数据未填写");
                            }

                            $psSizenameData[] = $v;
                            $psSizeData[] = $items;
                        } else {
                            unset($sizenameData[$k]);
                            unset($sizeData[$k]);
                        }
                    }
                    $skuData['ps_size_name'] = json_encode($psSizenameData);
                    $skuData['ps_size'] = json_encode($psSizeData);

                    $skuData['style_name'] = $this->request->param('style_name/s', '');
                    $skuData['sku_type'] = $this->request->param('sku_type/s', '');
                    $skuData['caichuang_position'] = $this->request->param('caichuang_position/d', '0');
                    $skuData['off_pressing_level'] = $this->request->param('off_pressing_level/d', '0');
                    $skuData['special_process_a_level'] = $this->request->param('special_process_a_level/d', '0');
                    $skuData['special_process_b_level'] = $this->request->param('special_process_b_level/d', '0');
                    $skuData['zj_level'] = $this->request->param('zj_level/d', '0');
                    $skuData['create_time'] = time();
                    $skuData['update_time'] = time();

                    $id = db('sku')->insertGetId($skuData);

                    // 处理产品材料
                    foreach ($customerDosageArr as $materialId => $val) {
                        $upData = [
                            'material_dosage' => arrayGet($materialDosageArr, $materialId, 0),
                            'customer_dosage' => arrayGet($customerDosageArr, $materialId, 0),
                            'accurate_dosage' => arrayGet($accurateDosageArr, $materialId, 0),
                            'update_time' => time(),
                        ];
                        $upData['sku_id'] = $id;
                        $upData['material_id'] = $materialId;
                        $upData['create_time'] = time();
                        $temp = db('sku_material')->insert($upData);

                        // 更新客户纸筒重量和空差
                        $upMaterialData = [];
                        $customerWeightPage = arrayGet($customerWeightPageArr, $materialId, 0);
                        $diffLength = arrayGet($diffLengthArr, $materialId, 0);
                        if ($customerWeightPage > 0) $upMaterialData['customer_weight_page'] = $customerWeightPage;
                        if ($diffLength > 0) $upMaterialData['diff_length'] = $customerWeightPage;
                        if ($upMaterialData) {
                            db('material')->where('id', $materialId)->update($upMaterialData);
                        }
                    }
                    $this->insertNewOrderData();
                }


                db()->commit();
                (new SkuService())->updatePicCache($skuData['sku']);

                return $this->Json(1);
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
        }

        $assign = [
            'oInfo'=>db("order")->order("id desc")->find(),
            'groupKV' => getGroupKV(0),
            'factoryOutgoKV' => getFactoryOutgoKV(1),
            'formData' => $formData,
            'factoryKV' => ['' => '请选择'] + getFactoryKV(true),
            'smList' => [],
            'sizeNameList' => ['' => '请选择'] + db('size')->order('id')->column('name', 'id'),
            'partList' => ['' => '请选择'] + getPartKV(),
            'partListAll' => db('part')->select(),
            'sizenameArr' => [],
            'partArr' => [],
            'measurementArr' => [],
            'sizeArr' => [],
            'processLevel' => config('mimo.process_level'),
            'caichuangPosition' => config('mimo.caichuang_position'),
            'xm_select_data' => (new SkuService())->_get_xm_select_data(),
        ];
        $template = $this->request->param('template', 'create_order');
        return $this->assign($assign)->fetch($template);
    }

	/**
	 * 订单编辑
	 */
	public function edit() {
		$orderId = $this->request->param('order_id/d', 0);
		$action=$this->request->param('action/s', '');
		if($action=='createOrder'){
		    return $this->createOrder();
        }
		$orderService = new OrderService();
		$skuService = new SkuService();
		$orderSizeService = new OrderSizeService();
		$orderMaterialService = new OrderMaterialService();
		$orderUserService = new OrderUserService();

		$orderInfo = $orderService->getInfoById($orderId);
		if (empty($orderInfo)) return $this->error('订单不存在');

		$skuInfo = $skuService->getInfoBySku($orderInfo['sku']);
		$orderSize = $orderSizeService->getListByOrderId($orderId);
		$orderMaterial = $orderMaterialService->getListByOrderId($orderId);
		$orderUser = $orderUserService->getListByOrderId($orderId);

		$groupKV = getGroupKV($orderInfo['factory_id']);

		if ($this->request->isAjax()) {
			try {

				db()->startTrans();

				$post = $this->request->param();
				$osOrderCount = arrayGet($post, 'os_order_count', []);
				$osShicaiCount = arrayGet($post, 'os_shicai_count', []);
				$osJiaohuoCount = arrayGet($post, 'os_jiaohuo_count', []);
				$osJiaohuoTailCount = arrayGet($post, 'os_jiaohuo_tail_count', []);
				$osDaohuoCount = arrayGet($post, 'os_daohuo_count', []);

				// 订单详细
				$orderData = [];
                switch (env('env_site')){
                    case 'riwei':
                        $orderData['ext_id'] = trim(arrayGet($post, 'ext_id'));
                        break;
                }
				$orderData['outgo_status'] = arrayGet($post, 'outgo_status');
                $orderData['dress_color'] = arrayGet($post, 'dress_color') ? $post['dress_color'] : $orderInfo['dress_color'];
				$orderData['outgo_time'] = arrayGet($post, 'outgo_time') ? strtotime($post['outgo_time']) : 0;
				$orderData['outgo_over_time'] = arrayGet($post, 'outgo_over_time') ? strtotime($post['outgo_over_time']) : 0;
				$orderData['caigou_over_time'] = arrayGet($post, 'caigou_over_time') ? strtotime($post['caigou_over_time']) : 0;
				$orderData['caichuang_over_time'] = arrayGet($post, 'caichuang_over_time') ? strtotime($post['caichuang_over_time']) : 0;
                //$orderData['chejian_over_time'] = arrayGet($post, 'chejian_over_time') ? strtotime($post['chejian_over_time']) : 0; //车间完成时间
                //$orderData['tail_over_time'] = arrayGet($post, 'tail_over_time') ? strtotime($post['tail_over_time']) : 0; //尾部完成时间
				$orderData['over_time'] = arrayGet($post, 'over_time') ? strtotime($post['over_time']) : 0;
				$orderData['real_shipment_count'] = array_sum($osDaohuoCount);
				if($orderData['real_shipment_count'] > 0) {
					$orderData['real_shipment_status'] = 1;
					$orderData['real_shipment_time'] = arrayGet($post, 'real_shipment_time') ? strtotime($post['real_shipment_time']) : time();
				}
				$orderData['update_time'] = time();

				if ($orderData['over_time'] == 0) $orderData['status'] = 1; // 重新标记订单未完成
				db('order')->where('id', $orderId)->update($orderData);

				// 尺码件数
				foreach ($osOrderCount as $mid => $val) {
					$orderSizeData = [
						'order_count' => $osOrderCount[$mid],
						'shicai_count' => $osShicaiCount[$mid],
						'jiaohuo_count' => $osJiaohuoCount[$mid],
						'daohuo_count' => $osDaohuoCount[$mid],
						'jiaohuo_tail_count' => $osJiaohuoTailCount[$mid],
						'update_time' => time(),
					];
					db('order_size')->where('mid', $mid)->update($orderSizeData);
				}

				// 裁床数据
				$zhahao = arrayGet($post, 'zhahao', []);
				$jianshu = arrayGet($post, 'jianshu', []);
				$sizeName = arrayGet($post, 'size_name', []);
				$chuanghao = arrayGet($post, 'chuanghao', []);
				//删除扎数
				$before=db('order_user')->where('order_id', $orderId)->column('zhahao');
				$dif=[];
				$dif = array_diff($before,$zhahao);
				if(!empty($dif)){
					foreach ($dif as $kd => $vd) {
						db('order_user')->where("order_id = {$orderId} and zhahao = {$vd}")->delete();
					}
				}
				$orderSizeArr = [];
				foreach ($zhahao as $key => $val) {
					$orderUserData = [
						'zhahao' => $val,
						'jianshu' => $jianshu[$key],
						'size_name' => $sizeName[$key],
						'chuanghao' => $chuanghao[$key],
						'update_time' => time(),
					];
					$info = db('order_user')->where("order_id = {$orderId} and zhahao = {$val}")->findOrEmpty();
					if ($info) {
						db('order_user')->where('mid', $info['mid'])->update($orderUserData);
					} else {
						$orderUserData['factory_id'] = $orderInfo['factory_id'];
						$orderUserData['order_id'] = $orderInfo['id'];
						$orderUserData['client_ordernum'] = $orderInfo['client_ordernum'];
						$orderUserData['create_time'] = time();
						db('order_user')->insertGetId($orderUserData);
					}
					$orderSizeArr[$sizeName[$key]][]=$jianshu[$key];
				}
				//同步更新order_size表
				foreach ($orderSizeArr as $k => $v) {
					$orderUserData = [
						'shicai_count' => array_sum($v),
						'update_time' => time(),
					];
					$where=[
						['order_id','=',$orderId],
						['size_name','=',$k]
					];
					db('order_size')->where($where)->update($orderUserData);
				}
				// 材料信息
				$customerDosages = arrayGet($post, 'customer_dosage', []);
				$materialDosage = arrayGet($post, 'material_dosage', []);
				foreach ($customerDosages as $materialId => $customerDosage) {
					$omData = [
						'customer_dosage' => $customerDosage,
						'material_dosage' => $materialDosage[$materialId],
						'update_time' => time(),
					];
					db('order_material')->where("order_id = {$orderInfo['id']} and material_id = {$materialId}")->update($omData);

					$smData = [
						'customer_dosage' => $customerDosage,
						'material_dosage' => $materialDosage[$materialId],
					];
					db('sku_material')->where("sku_id = {$skuInfo['id']} and material_id = {$materialId}")->update($smData);
				}

				$this->addOrderLog($orderId, $orderInfo['client_ordernum'], "编辑保存");

				db()->commit();
				return $this->Json(1, '修改订单成功');
			} catch (\Exception $e) {
				db()->rollback();
				return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
			}
		}

		$assign = [
			'factoryKV' => getFactoryKV(true),
			'factoryOutgoKV' => getFactoryOutgoKV(1),
			'groupKV' => $groupKV,
			'orderId' => $orderId,
			'oInfo' => $orderInfo,
			'sInfo' => $skuInfo,
			'osList' => $orderSize,
			'omList' => $orderMaterial,
			'ouList' => $orderUser,
			'sizeNameArr' => array_unique(array_column($orderSize, 'size_name')),
		];
		return $this->assign($assign)->fetch();
	}

	/**
	 * 材料操作日志
	 *
	 * @author KING
	 * @date 2020年7月7日
	 *
	 * @return \think\response\Json|string
	 */
	public function materialLog()
	{
		$factoryKV = [0 => ''] + getFactoryKV(true);
		$stallsKV = [0 => ''] + getStallsKV();
		$systemUserKV = [0 => ''] + getSystemUserKV(null);
		$clientOrdernum    = $this->request->param('client_ordernum/s');
		if ($this->request->isAjax()) {
			$where    	= [];
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$factoryId    = $this->request->param('factory_id/d');
			$stallsId    = $this->request->param('stalls_id/d');
			$materialType = $this->request->param('materialType','');
			$clientOrdernum    = $this->request->param('client_ordernum/s');
			$materialName    = $this->request->param('material_name/s');
			$createTimeRange    = $this->request->param('create_time_range/s');

			if ($factoryId != '') {
				$where[] = ['factory_id', '=', $factoryId];
			}
			if ($stallsId != '') {
				$where[] = ['stalls_id', '=', $stallsId];
			}
            if ($materialType != '') {
                $where[] = ['material_type', '=', $materialType];
            }
			if ($clientOrdernum != '') {
				$where[] = ['client_ordernum', '=', $clientOrdernum];
			}
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    if ($ext_id != '') {
                        $temp = db('order')->field('id')->where([['ext_id', '=', $ext_id]])->find();
                        $where[] = ['order_id', '=', $temp['id']];
                    }
                    break;
            }
			if ($materialName != '') {
				$where[] = ['material_name', 'like', "'%".$materialName."%'"];
			}
			if ($createTimeRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $createTimeRange));
                $where[] = ['create_time', 'between', [$startTime, $endTime]];
			}

			$order = 'id DESC';
			$data['data'] = db('order_material_log')->where($where)->page($page)->limit($limit)->order($order)->select();
			$materialService = new MaterialService();
			$orderService = new OrderService();
			foreach ($data['data'] as $k => $v) {
				$data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
				$data['data'][$k]['stalls_name'] = arrayGet($stallsKV, $v['stalls_id'], '');
				$data['data'][$k]['admin_name'] = arrayGet($systemUserKV, $v['admin_id'], '');
				$data['data'][$k]['sku'] = $orderService->getSkuByClientOrdernum($v['client_ordernum']);
                $data['data'][$k]['type_txt'] = '删除';
                switch ($data['data'][$k]['type']) {
                    case 1:
                        $data['data'][$k]['type_txt'] = '打标';
                        break;
                    case 2:
                        $data['data'][$k]['type_txt'] = '删除';
                        break;
                    case 3:
                        $data['data'][$k]['type_txt'] = '发货';
                        break;
                }
			}
			$data['count'] = db('order_material_log')->where($where)->count('id');
			$data['code'] = 0;
			$data['msg'] = '';
			return json($data);
		}

		$assign = [];
		unset($factoryKV[0]);
        $assign['materialType']=[''=>'请选择','fabric'=>'面料/里料','accessories'=>'辅料'];
		$assign['factoryKV'] = $factoryKV;
		$assign['stallsKV'] = $stallsKV;
		$assign['clientOrdernum'] = $clientOrdernum;
		$assign['alert'] = $this->request->param('alert/d', 0);

		return $this->assign($assign)->fetch();
	}

	/**
	 * 订单操作日志
	 *
	 * @author KING
	 * @date 2020年7月30日
	 *
	 * @return array
	 */
	public function log()
	{
		if ($this->request->isAjax()) {
			$where      = $data = [];
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$clientOrdernum    = $this->request->param('client_ordernum/s');
			$keyword    = $this->request->param('keyword/s');
			$createDateRange    = $this->request->param('create_date_range/s');
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    if ($ext_id != '') {
                        $temp = db('order')->field('id')->where([['ext_id', '=', $ext_id]])->find();
                        $where[] = ['olg.order_id', '=', $temp['id']];
                    }
                    break;
            }

            //订单加一级
            order_level($where,'o.');
            if (substr($clientOrdernum, 0, 1) == 'B') {
                $where[] = ['olg.order_material_id', '=', substr($clientOrdernum, 1, 10)];
            } else {
                $clientOrdernum != '' && $where[] = ['olg.client_ordernum', '=', $clientOrdernum];
            }
			if ($keyword) {
				$where[] = ['olg.remark', 'like', "%{$keyword}%"];
			}
			if ($createDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
				$where[] = ['olg.create_time', 'between', [$startTime, $endTime+86399]];
			}

			$order = 'olg.id desc';
			$data['data'] = db('order_log olg')
                ->field('olg.*')
                ->join('order o', 'olg.order_id=o.id', 'left')
                ->where($where)->page($page)->limit($limit)->order($order)->select();
			$data['count'] = db('order_log olg')
                ->join('order o', 'olg.order_id=o.id', 'left')
                ->where($where)->count();
			$data['code'] = 0;
			$data['msg'] = '';
			return json($data);
		}

		$assign = [
			'systemUserKV' => getSystemUserKV(null)
		];
		return $this->assign($assign)->fetch();
	}

	/**
	 * 手动同步订单
	 *
	 * @author King
	 * @date 2020年8月10日
	 *
	 */
	public function sync() {
		$dateRange  = $this->request->param('sync_date_range/s', '');
		$orderFromArr  = $this->request->param('order_from/a', []);
		$clientOrdernum  = $this->request->param('client_ordernum/s', '');

		if (empty($dateRange) && empty($clientOrdernum)) {
			return $this->Json(0, '参数错误');
		}

		if ($dateRange != '') {
			list($startTime, $endTime) = array_map('strtotime', explode('~', $dateRange));
			if (date('Ymd', $startTime) != date('Ymd', $endTime)) {
				return $this->Json(0, '不允许跨天请求');
			}
		}

		if ($clientOrdernum == '') {
			$res = [
				'code' => 1,
				'msg' => '同步订单成功',
				'data' => [],
			];

			$orderFromConfig = config('mimo.order_from');
			$msgArr = [];
			$dataArr = [];
			$successNum = 0;
			$failNum = 0;
			foreach ($orderFromConfig as $k => $v) {
				if (empty($orderFromArr) || in_array($k, $orderFromArr)) {
					$output = Console::call('cronSyncOrder', ['--print=0','--start='.$startTime,'--end='.$endTime, '--mes='.$k, '--force=1']);
					$resA = json_decode($output->fetch(), true);
					if ($resA['code'] == 0) {
						$msgArr[] = "[{$v}]" . $resA['msg'];
						$failNum++;
					} else {
						$dataArr[$v] = $resA['data'];
						$successNum++;
					}
				}
			}

			if ($failNum > 0 && $successNum == 0) {
				$res['code'] = 0;
				$res['msg'] = "同步失败！<br>".implode('<br>', $msgArr);
			} else if($failNum > 0 && $successNum >= 0) {
				$res['msg'] = "部分同步失败！<br>".implode('<br>', $msgArr);
			}
			$res['data'] = $dataArr;
			return $this->Json($res['code'], $res['msg'], $res['data']);
		} else {
			$output = Console::call('cronSyncOrder', ['--print=0','--client_ordernum='.$clientOrdernum]);
			$res = json_decode($output->fetch(), true);
			if ($res['code'] == 1) {
				$data['code'] = 1;
				$data['msg'] = '同步订单成功';
				$data['data'] = $res['data'];
			} else {
				$data['code'] = 0;
				$data['msg'] = '同步订单失败，'. $res['msg'];
				$data['data'] = $res['data'];
			}
			$this->addOrderLog(0, $clientOrdernum, '同步指定订单'.$clientOrdernum);
			return $this->Json($data['code'], $data['msg'], $data['data']);
		}
	}

	/**
	 * 更新材料日志表中的材料使用量
	 *
	 * @author KING
	 * @date 2014-6-11
	 *
	 * @param int $orderId	订单ID
	 * @return boolean
	 */
	private function _updateMaterialLog($orderId) {
		if (!$orderId) return false;
		$orderMaterialList = (new OrderMaterialService())->getListByOrderId($orderId);
		foreach ($orderMaterialList as $k => $v) {
			$materialId = $v['material_id'];
			$useNum = $v['shiji_caigou_count'] - $v['yuque_count']; // 材料使用量 = 开单采购量 - 余缺量
			$upData = array();
			$upData['use_num'] = $useNum;
			$upData['update_time'] = time();
			db('material_log')->where(['order_id' => $orderId, 'material_id' => $materialId])->update($upData);
		}
		return true;
	}
	/**
	 * 同步至金鹏
	 *
	 * @author 飞燕
	 * @date 2021-4-23
	 *
	 * @param int $orderId	订单ID
	 * @return boolean
	 */
	public function syncJinpeng() {
		$orderId  = $this->request->param('order_id/d', 0);
		$action  = $this->request->param('action/s', 'add');
		$orderService = new OrderService();
		$orderUserService = new OrderUserService();
		$jp=new Jinpeng();

		$oInfo = $orderService->getInfoById($orderId);
		$detail=$detail1=$msgArr=[];
		if (!$oInfo) {
			return $this->Json(0, '参数错误');
		}
		$ouList=$orderUserService->getListByOrderId($orderId);
		if (!$ouList) {
			return $this->Json(0, '扎号不存在');
		}
		try {
			//同步金鹏订单
			if($oInfo['jinpeng_status']!=1 || $action=="dele"){
				$res1=$orderService->syncJinpengOrder($orderId,$action);
				$msgArr[]=$res1['msg'];
			}
			//同步金鹏订单裁剪扎数
			if($action!="dele"){
				$res2=$orderService->syncJinpengCut($orderId,$action,$action);
				foreach ($res2['msg'] as $km => $vm) {
					$msgArr[]=$vm;
				}
			}
			$data['code']=1;
			$data['msg']="";
			if(isset($res1) && $res1['succeed']==true){
				$data['code']=1;
				$data['msg']="同步成功";
			}else{
				$data['code']=0;
				$data['msg']="同步失败!<br>".implode('<br>', $msgArr);
			}
			$this->addOrderLog($orderId, $oInfo['client_ordernum'], "同步金鹏订单（{$action}），" . $data['msg']);
			return $this->Json($data['code'], $data['msg']);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}
}